package oo

import (
	"elegantGo/chapter17/controller/response"
	"elegantGo/chapter17/oo/article"
	"elegantGo/chapter17/oo/primitive"
	"fmt"
)

type PaidArticle struct {
	baseArticle
	article.ContentMasker

	saleCount     article.SaleCount
	price         primitive.Fen
	discountPrice primitive.Fen

	orders ArticleOrders
}

func (oo *PaidArticle) DiscountPriceCalculate(calculateFunc func(int) int) {
	oo.discountPrice.SetValue(calculateFunc(oo.GetPrice()))
}

func (oo *PaidArticle) GetSaleCount() int {
	return oo.saleCount.Value()
}

func (oo *PaidArticle) SetSaleCount(v int) {
	oo.saleCount.SetValue(v)
}

func (oo *PaidArticle) GetPrice() int {
	return oo.price.Value()
}

func (oo *PaidArticle) SetPrice(v int) error {
	minimumPrice := primitive.Fen{}
	minimumPrice.SetValue(1000)

	if v < minimumPrice.Value() {
		return fmt.Errorf("最低价为：%f元", minimumPrice.ToYuan())
	}

	oo.price.SetValue(v)
	return nil
}

func (oo *PaidArticle) GetDiscountPrice() int {
	return oo.discountPrice.Value()
}

func (oo *PaidArticle) SetDiscountPrice(v int) {
	oo.discountPrice.SetValue(v)
}

func (oo *PaidArticle) Orders() ArticleOrders {
	return oo.orders
}

func (oo *PaidArticle) SetOrders(orders ArticleOrders) {
	oo.orders = orders
}

func (oo *PaidArticle) IsPaid(sessionUser User) bool {
	if sessionUser == nil {
		return false
	}
	return oo.orders.IsPaid(sessionUser)
}

func (oo *PaidArticle) Mapper() *response.Article {
	if oo == nil {
		return nil
	}

	respArticle := oo.baseArticle.Mapper()
	respArticle.Content = oo.GetContent()
	respArticle.Price = oo.price.ToYuan()
	respArticle.DiscountPrice = oo.discountPrice.ToYuan()
	respArticle.SaleCount = oo.saleCount.ValuePtr()

	return respArticle
}
